<?php
namespace Home\Controller;
use Think\Controller;
vendor('taobao.TopSdk');//引入淘宝SDK

class 	ExpressController extends Controller {
	
	public function __construct() {
		parent::__construct();
		$ti = M('ti') -> where("user_id = '".$_SESSION['user']['id']."'") -> find();
		
		if(empty($ti) || empty($_SESSION['user']['id']))
		{
			$this->redirect('Home/Login/login');
		}
    }
	
	//查询快递公司
	
	
	public function index(){
		$print_template = M('print_template') -> order('id asc') -> select();
		$region = M('region') -> where("parent_id = 1") -> select();
		
		//dump($region);die;
		$this -> assign("data",$data);
		$this -> assign("print_template",$print_template);
		$this -> assign("region",$region);
		$this->display();
    }
	
	public function region_find(){
		$id=empty($_REQUEST['id'])?'':$_REQUEST['id'];
		$name=empty($_REQUEST['name'])?'':$_REQUEST['name'];
		if($id && $name){
			$where['print_id']   = $id;
			$where['print_name'] = $name;
			$where['visitor_admin'] = $_SESSION['user']['id'];
			$res = M('feright') -> where($where) -> field('content') -> find();
			if($res){
				$data['msg'] = 'success';
				$data['diqu'] = unserialize($res['content']);
			}else{
				$data['msg'] = 'error';
			}
			echo json_encode($data);die;
		}
	}
	
	public function muban_add(){
		if($_POST['print_name'] && $_POST['print_id']){
			$data['print_name'] 	= trim(I('print_name'));
			$data['print_id'] 		= trim(I('print_id'));
			$diqu 					= I('diqu');
			$data['content'] 		= serialize($diqu);
			$data['visitor_admin'] 	= $_SESSION['user']['id'];
			$where['print_name'] 	= $data['print_name'];
			$where['visitor_admin'] = $data['visitor_admin'];
			
			$res = M('feright') -> where($where) -> find();
			if($res){
				$rest = M('feright') -> where($where) -> save($data);
			}else{
				$rest = M('feright') -> add($data);
			}
			
			if($rest){
				$this->success('添加成功！','index');die;
			}else{
				$this->error('没有更改的数据！','index');die;
			}
			
		}else{
			$this->error('请选择快递模板！','index');die;
		}
		
	}
	/*
	public function template_list(){
		$Region = D('region');
		$region_list = $Region->get_template_list();
		$this->assign('region_list',$region_list);
		$this->display();
		}
	*/

	
	
	/* 运费导入处理  */
	public function import_postage() 
    {   
		
	    $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('xls', 'xlsx');// 设置附件上传类
        $upload->rootPath  =     './Public/excel/'; // 设置附件上传根目录
        // 上传文件
        $info   =   $upload->uploadOne($_FILES['excel']);
	
        $filename = './Public/excel/'.$info['savepath'].$info['savename'];
        $exts = $info['ext'];
     
        if(!$info)
		 {// 上传错误提示错误信息
              $this->error($upload->getError());
         }
		 else
		 {
			vendor('PHPExcel180.PHPExcel');
			//创建PHPExcel对象，注意，不能少了\
			$PHPExcel=new \PHPExcel();
			//如果excel文件后缀名为.xls，导入这个类
			if($exts == 'xls'){
				import("Org.Util.PHPExcel.Reader.Excel5");
				$PHPReader=new \PHPExcel_Reader_Excel5();
			}else if($exts == 'xlsx'){
				import("Org.Util.PHPExcel.Reader.Excel2007");
				$PHPReader=new \PHPExcel_Reader_Excel2007();
			}
			
			$data=array();
			$data_sum=array();
	
	
			//载入文件
			$PHPExcel=$PHPReader->load($filename);
			//获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
			$currentSheet=$PHPExcel->getSheet(0);
			//获取总列数
			$allColumn=$currentSheet->getHighestColumn();
			//获取总行数
			$allRow=$currentSheet->getHighestRow();
			//循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
			for($currentRow=1;$currentRow<=$allRow;$currentRow++){
				//从哪列开始，A表示第一列
				for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
					//数据坐标
					$address=$currentColumn.$currentRow;
					//读取到的数据，保存到数组$arr中
					$cell =$currentSheet->getCell($address)->getValue();
	
					if($cell instanceof PHPExcel_RichText){
						$cell  = $cell->__toString();
					}
					
					$data[$currentColumn]=$cell;
				}
				
				if($currentRow>1)
				{
					$data_sum[$currentRow]=$data;
				}
				
	            
			}  
			
			
			$express_weight=M('express_weight');
			
			if(!empty($data_sum))
			{   
				$postage_data['group']  = time().rand(1000,9999);
				$visitor_id = $_SESSION['user']['id'];
				$shouquan = M('shouquan') -> field('group_id') -> where("visitor_id = '$visitor_id'") -> find();
				if($shouquan['group_id']){
					 $shouquan2 = M('shouquan') -> field('visitor_id') -> where("group_id = '".$shouquan['group_id']."'") -> select(); 	
					 foreach($shouquan2 as $k=> $val){
						 if($k == '0'){
							 $s_str = "'".$val['visitor_id']."'";
						 }else{
							 $s_str .= ","."'".$val['visitor_id']."'";
						 }
					 }
				 }
				foreach($data_sum as $k=>$v)
				{
					if(!empty($v['A']))
					{   
						$join = "trades as t on t.tid = o.tid";
						if($shouquan['group_id']){
					    	$suppinfo=M('orders') -> alias(' as o ')->field('o.id,o.logistics_company,receiver_state,t.title,o.visitor_id') -> join($join)->where("invoice_no = '".$v['A']."' and o.visitor_id in($s_str)")->find();
							
						}else{
							$suppinfo=M('orders') -> alias(' as o ')->field('o.id,o.logistics_company,receiver_state,t.title,o.visitor_id') -> join($join)->where("invoice_no = '".$v['A']."' and o.visitor_id = '".$_SESSION['user']['id']."'")->find();
						}
						if(!$suppinfo)
						{
							//$result['error'][$k][$v['A']]=1;
							//$result['error'][$k]['message']='货源 '.$v['A'].' 不存在，不能导入';
							$str.="运单号 ".$v['A']." 不存在，不能导入<br>";
							continue; 
						}
						
						/*$expressinfo=M('express')->field('id,title')->where("title = '".$v['C']."'")->find();
						if(!$expressinfo)
						{
							//$result['error'][$k][$v['C']]=1;
							//$result['error'][$k]['message']='快递 '.$v['C'].' 不存在，不能导入';
							$str.="快递 ".$v['C']." 不存在，不能导入<br>";
							continue; 
						}*/
						
						if(!preg_match("/^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/", $v['B'], $m)){
							$str.=$v['A']." 导入非法重量<br>";
							continue; 
						}
						$feright = M('feright') -> field('content') -> where("print_name ='".$suppinfo['logistics_company']."'") -> find();
						if(!$feright){
							$str.=$v['A']."".$suppinfo['logistics_company']." 没有设置运费模板<br>";
							continue; 
						}
						$fer_arr	=	unserialize($feright['content']);
						foreach($fer_arr as $k=>$val){
							if(strstr($suppinfo['receiver_state'],$k)){
								if($v['B']>$val['shouzhong']){
									$sheng = ceil($v['B']-$val['shouzhong']);
									$postage_data['freight'] = $sheng*$val['xufei']+$val['shoufei'];
								}else{
									$postage_data['freight'] = $val['shoufei'];
								}
							}
						}
						$postage_data['shop']=$suppinfo['title'];
						$postage_data['visitor_id']=$suppinfo['visitor_id'];
						$postage_data['logistics_company']=$suppinfo['logistics_company'];
						$postage_data['receiver_state']=$suppinfo['receiver_state'];
					    $postage_data['invoice_no']=$v['A'];
						$postage_data['weight']=$v['B'];
						
						
						$where['invoice_no']=$v['A'];
						
						$postageinfo=$express_weight->where($where)->find();
						
						if($postageinfo)
						{
							$res=$express_weight->where($where)->save($postage_data);
							
							if($res!==false)
							{    
							}
							else
							{
								$str.=$v['A']." 导入失败<br>";
							}
							
						}
						else
						{
							$res=$express_weight->add($postage_data);
							if($res)
							{   
							} 
							else
							{
								$str.=$v['A']." 导入失败<br>";
							}
						}
						
					}
					
				}
				
				if(!empty($str))
				{   
				    $str.="其余导入成功";
					$this->error($str,U('daoru',array('group'=>$postage_data['group'])));
				}
				else
				{
					$this->success('导入成功',U('daoru',array('group'=>$postage_data['group'])));
				}
				
				
			}else{
				$this->error('没有数据');
			}
			
         }
     
    }
	
	public function daoru(){
		$pageNo=empty($_REQUEST['pageNo'])?1:$_REQUEST['pageNo'];
		$pageSize=empty($_REQUEST['pageSize'])?10:$_REQUEST['pageSize'];
		$where['group'] = empty($_REQUEST['group'])?"":$_REQUEST['group'];
		if($where){
			$count['count']		=	M('express_weight') -> where($where)->count();
			$count['countpage']	=	ceil($count['count']/$pageSize);
			if($pageNo>=$count['countpage']){
				$pageNo=$count['countpage'];
			}
			if($pageNo<=0){
				$pageNo=1;
			}
			$express_weight = M('express_weight') -> where($where)->limit(($pageNo-1)*$pageSize,$pageSize)-> select();
			$count['pageSize']=$pageSize;
			$count['pageNo']=$pageNo;
			$count['num']=$count['countpage']-4;
			$this -> assign("count",$count);
			$this -> assign("express_weight",$express_weight);
		}
		$this->display();
    }
	 
	public function freight(){
		$pageNo=empty($_REQUEST['pageNo'])?1:$_REQUEST['pageNo'];
		$pageSize=empty($_REQUEST['pageSize'])?10:$_REQUEST['pageSize'];
		/*$feright = M('feright') -> where("visitor_admin = '".$_SESSION['user']['id']."'") -> field('print_name') -> select();
		if($feright){
			$where = "( 0";
			foreach($feright as $val){
				$where.=" or logistics_company = '".$val['print_name']."'";
			}
			$where.=")";
			$where.=" and visitor_id ='".$_SESSION['user']['id']."'";*/
			$visitor_id = $_SESSION['user']['id'];
			$shouquan = M('shouquan') -> field('group_id') -> where("visitor_id = '$visitor_id'") -> find();
			if($shouquan['group_id']){
				 $shouquan2 = M('shouquan') -> field('visitor_id') -> where("group_id = '".$shouquan['group_id']."'") -> select(); 	
				 foreach($shouquan2 as $k=> $val){
					 if($k == '0'){
						 $s_str = "'".$val['visitor_id']."'";
					 }else{
						 $s_str .= ","."'".$val['visitor_id']."'";
					 }
				 }
				 $where= "  visitor_id in($s_str)";
			 }else{
				 $where = " visitor_id = '$visitor_id'";
			 }		
			$count['count']		=	M('express_weight') -> where($where)->count();
			$count['countpage']	=	ceil($count['count']/$pageSize);
			if($pageNo>=$count['countpage']){
				$pageNo=$count['countpage'];
			}
			if($pageNo<=0){
				$pageNo=1;
			}
			$express_weight = M('express_weight') -> where($where)->limit(($pageNo-1)*$pageSize,$pageSize)-> select();
			$count['pageSize']=$pageSize;
			$count['pageNo']=$pageNo;
			$count['num']=$count['countpage']-4;
			
			$this -> assign("count",$count);
			$this -> assign("express_weight",$express_weight);
		//}
		$this -> display();
	}	

		
}
















